package week04

import "fmt"

// 变长无前缀编码
var EncodingRuleDefault = map[byte]string{
	'A': "0",
	'B': "10",
	'C': "110",
	'D': "111",
}

/*
功能: 求编码效率

    @description: 给定字符集合S={S1, S2, ..., Sn}, 求Σfi*Li

    @param rule map[byte]string  一套符号编码
    @param S [string]            符号集合
	@return [float64]            码位均值
*/
func EncodingEfficiency(rule map[byte]string, S string) float64 {
	fmt.Println("给与的符号集合: ", S)

	var totalChar = make(map[byte]int, 0)

	for i := 0; i < len(S); i++ {
		if _, exist := rule[S[i]]; exist {
			totalChar[S[i]]++
		}
	}
	// 每个符号出现的频率f1 ~ fn
	fi, average := 1e-2, 1e-2 // default 0.01
	for k, v := range totalChar {
		fi = float64(v) / float64(len(S))
		Li := len(rule[k])
		fmt.Printf("%c  %d 个  码位L= %d  频率f= %3.2f\n", k, v, Li, fi)

		average += fi * float64(Li)
	}

	fmt.Printf("码位均值 Σfi*Li = %.3f\n", average)
	return average
}
